// 权限控制

import router from './router'
import { asyncRoutes } from './router/asyncRoute'
import { getCookie } from './utils/auth'
import store from './store'
import { TOKEN_KEY } from './constants/KEY'

const WHITE_LIST = ['/login', '/404']

function getMenuList(permissions) {
  const list = permissions.map(item => item.split(':'))
  return {
    menus: [...new Set(list.map(item => item[0]))],
    smenus: [...new Set(list.map(item => `${item[0]}:${item[1]}`))]
  }
}

function getFilterRoutes(menuObj, asyncRoutes) {
  // 如果是管理员不做任何过滤
  if (menuObj.smenus.includes('*:*')) return asyncRoutes

  const filterRoutes = asyncRoutes
    .filter(route => menuObj.menus.includes(route.permission))
    .map(item => ({
      ...item,
      children: item.children.filter(item => menuObj.smenus.includes(item.permission))
    }))
  return filterRoutes
}

router.beforeEach(async(to, from, next) => {
  const token = getCookie(TOKEN_KEY)
  // 有token
  if (token) {
    next()
    // 获取用户信息
    if (!store.state.user.profile.id) {
      // 1. 获取原始权限列表
      const permissions = await store.dispatch('user/getProfile')
      // 2. 获取菜单权限列表
      const menuObj = getMenuList(permissions)
      console.log(menuObj)
      // 3. 通过菜单权限过滤一级和二级
      const filterRoutes = getFilterRoutes(menuObj, asyncRoutes)
      console.log(filterRoutes)
      // 4. addRoute动态添加
      filterRoutes.forEach(route => router.addRoute(route))
      // 5. 存入Vuex渲染左侧菜单
      store.commit('menu/setMenuList', filterRoutes)
    }
  } else {
    // 没有token
    if (WHITE_LIST.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
